<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Myaccount extends AdminController {
	
	function Myaccount (){
		parent::AdminController();
		
		$this->load->library('redux_auth');
		$this->load->model("redux_auth/users_model", "Users");
		$this->load->config("redux_auth");
	}
	
	function index(){
		/*$additional_columns = $this->config->item('columns');
		$this->_addData("additional_columns", $additional_columns);
		
		$user = $this->redux_auth->profile();
		$this->_addData("user", $user);
		$this->_render();*/
		
		$additional_columns = $this->config->item('columns');
		$identity = $this->config->item('identity');
		
		$this->load->library('Form_validation');
		
		$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email|valid_email|callback_email_check');
		
		$this->form_validation->set_rules('change_password', 'Change Password');
		
		if($this->input->post("change_password") == "change"){
			$this->form_validation->set_rules('password', 'Contraseña', 'trim|required');
			$this->form_validation->set_rules('passconf', 'Confirmación de contraseña', 'trim|required|matches[password]');
		}
		
		if (!empty($additional_columns))
	    {
	        foreach ($additional_columns as $column)
	        {
	            $this->form_validation->set_rules($column, '');
	        }
	    }
		
		if ($this->form_validation->run() == TRUE){
			
			$identity_value = $this->redux_auth->profile()->{$identity};
			
			if($this->input->post("change_password") == "change"){
				$this->redux_auth->change_password($identity_value, $this->input->post("password"));
			}
			
			//Actualizar Info
			$additional_info = array();
			if (!empty($additional_columns))
		    {
		        foreach ($additional_columns as $column)
		        {
		            $additional_info[$column] = $this->input->post($column);
		        }
		    }
		    
		    $this->redux_auth->change_user_info($identity_value, $additional_info);
			
			$this->_addFlashSuccess("Perfil actualizado correctamente");
			
			redirect("admin/myaccount");
		} else{
			$this->_addData("additional_columns", $additional_columns);
			
			$user = $this->redux_auth->profile();
			$this->_addData("user", $user);
			$this->_render();
		}
	}
	
	/**
	 * Email check
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function email_check($email)
	{
		//Comprobamos si el usuario no ha cambiado su email
		$profile = $this->redux_auth->profile();
		if($profile->email == $email){
			return true;
		}
		
	    $check = $this->Users->email_check($email);
	    
	    if ($check)
	    {
	        $this->form_validation->set_message('email_check', 'The email "'.$email.'" already exists.');
	        return false;
	    }
	    else
	    {
	        return true;
	    }
	}
}